﻿using Kinlo.Entitys;
using NewLife.Data;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using UIWindows.Domains;
using UIWindows.GlobalStatics;
using UIWindows.Models.Homes;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using UIWindows.Views;
using XCode;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models.PLCInteraktion;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClassAttribute(TaskTypes.前称重)]
    public class BeforeWeighing : ServierBase
    {
        private volatile int _lock = 0;
        protected void Locked()
        {
            int lockNumber = 0;
            while (Interlocked.Exchange(ref _lock, 1) != 0)
            {
                _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0; _ = 0;
                if (++lockNumber > 50)
                {
                    Thread.Sleep(1);
                    lockNumber = 0;
                }
            }
        }

        protected void UnLock() => Interlocked.Exchange(ref _lock, 0);
        private SnowflakeManager _snowflake;
        static object locker = new object();
        private volatile int _weighingNG = 0, _total = 0, _lessLiquid = 0, _multiLiquid = 0, _LeakDetectionNG = 0;
        public BeforeWeighing(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig, UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic) :
            base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {
            _snowflake = new SnowflakeManager(12);
        }

        public override Task Handle(DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            try
            {
                //var beforeWeighingModel = _systemConfig.IAddressList.FirstOrDefault(x=>x.ServiceName == context.ServiceName);
                //var beforeWeighingModel = _systemConfig.IAddressList.FirstOrDefault(x=>x.ServiceName == context.ServiceName);
                //if (beforeWeighingModel == null)
                //{
                //    RunLog($"找不到号设备55555555555", MessageLevelType.错误);
                //    return base.Handle(context);
                //}
                _weighingNG = _total = _lessLiquid = _multiLiquid = _LeakDetectionNG = 0;
  
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
                DateTime weighing_time = DateTime.Now;

                bool alarm = false;
                var erinnerungen = ReadErinnerungen(plc, context.Address_Struct, context.Struct_Length, _systemConfig.IAddress.Erinnerungen_BeforeWeighing, context.AddressingMethod);


                Models.Devices.DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == context.TaskType
          && x.DeviceType == context.DeviceType && x.Index == 1);
                if (device == null)
                {
                    RunLog($"找不到[{1}]号设备", MessageLevelType.错误);
                    WriteResult("", ResultTypes.不合格, plc, context.Address_Struct, context);


                    return base.Handle(context);
                }

              

                //生成虚拟码
                var barCode = GenerateUniqueBarcode(_parameterStatic.WeighingConfig.CurrentLocation.ToString("D2"));

                var address_Struct = "PC_Result_Scales.BeforeWeight[0]";
                //称重
                double? weiging = default;
                weiging = GetWeiging(device, barCode);
                if ((weiging == null || weiging < 20) && !_parameterStatic.DecideParameter.EnableEmptyRun)
                {
                    RunLog($"[{barCode}] [{1}]号不稳定报警", MessageLevelType.警告);
                    alarm = true;
                    //WriteResult(barCode, ResultTypes.不合格, plc, address_Struct, context);
                    WriteCMD(1, plc, _systemConfig.IAddress.Alarm_BeforeWeighing);
                    return base.Handle(context);
                }

                if (_parameterStatic.WeighingConfig.IsInitialized)
                {
                    //var weighingType = _parameterStatic.WeighingConfig.ScaleType == TaskTypes.前称重 ? 1 : 2;
                    ////1前称 2后称
                    //plc.WriteSingle((float)weighingType, "PC_Result_Scales.BeforeWeight[3].PLCData");
                    _parameterStatic.WeighingConfig.CurrentLocation = 0;
                    _parameterStatic.WeighingConfig.IsInitialized = false;
                }

                _parameterStatic.WeighingConfig.CurrentLocation++;

                var position = _parameterStatic.WeighingConfig.CurrentLocation;
                DateTime dateTime = DateTime.Now;
               
                var entity = new ProductionData();
                //判断是前称还是后称
                if (_parameterStatic.WeighingConfig.ScaleType == TaskTypes.前称重)
                {
                    ProductionData.Meta.TableName = $"ProductionData_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}";

                    long snowflake = _snowflake.NextId();
                    //string rangeForeweigh = _parameterStatic.DecideParameter.EnableReinvestmentMode 
                    //    ? $"{_parameterStatic.RangeParameter.ReinvestmentWeighBeforeDown}-{_parameterStatic.RangeParameter.ReinvestmentWeighBeforeUp}" 
                    //    : $"{_parameterStatic.RangeParameter.WeighBeforeDown}-{_parameterStatic.RangeParameter.WeighBeforeUp}";
                    //string rangeFluidRate = _parameterStatic.DecideParameter.EnableVariableInjection
                    //        ? $"{_parameterStatic.RangeParameter.VariablesDown}-{_parameterStatic.RangeParameter.Variables}-{_parameterStatic.RangeParameter.VariablesUp}"
                    //        : $"{_parameterStatic.RangeParameter.QuantitativeDown}-{_parameterStatic.RangeParameter.Quantitative}-{_parameterStatic.RangeParameter.QuantitativeUp}";


                    //weiging = GetWeiging(device, entity.BarCode);

                    //if ((weiging == null || weiging < 20) && !_parameterStatic.DecideParameter.EnableEmptyRun)
                    //{
                    //    RunLog($"[{entity.BarCode}] [{1}]号不稳定报警", MessageLevelType.警告);
                    //    alarm = true;
                    //    _parameterStatic.WeighingConfig.CurrentLocation--;
                    //    WriteCMD(1, plc, _systemConfig.IAddress.Alarm_BeforeWeighing);

                    //    return base.Handle(context);
                    //}
                    RunLog($"前称重触发，电池位置[{position}]", MessageLevelType.警告);
                    // 计算行号
                    var row = (position - 1) / 6 + 1;

                    // 计算列号
                    var column = (position - 1) % 6 + 1;

                    _homeStatic.ChartData.Total_Inbound += 1;

                    entity = new ProductionData()
                    {
                        SnowflakeId = snowflake,
                        FormerWeighing = weiging == null ? 0 : (double)weiging,
                        NetWeight= weiging == null ? 0 : (double)weiging,
                        BarCode = barCode,
                        LocationFormerWeighing=(byte)position,
                        //TimeScanCodeBefore = dateTime.GetJSTimeUtc(),
                        TimeFormerWeighing = dateTime.GetJSTimeUtc(),
                        RangeElectrodes = $"{_parameterStatic.RangeParameter.ElectrodesDown}={_parameterStatic.RangeParameter.ElectrodesUP}",
                        RangeAfterWeighing = $"{_parameterStatic.RangeParameter.WeighAfterDown}-{_parameterStatic.RangeParameter.WeighAfterUp}",
                        RangeForeweigh = $"{_parameterStatic.RangeParameter.WeighBeforeDown}-{_parameterStatic.RangeParameter.WeighBeforeUp}",
                        RangeFluidRate = $"{_parameterStatic.RangeParameter.QuantitativeDown}-{_parameterStatic.RangeParameter.Quantitative}-{_parameterStatic.RangeParameter.QuantitativeUp}",
                        BatchElectrolyte = _parameterStatic.CollectionItemsParameter.BatchElectrolyte,
                        ProductType = _parameterStatic.CollectionItemsParameter.ProductType.ToString(),
                        GlueNailBatch = _parameterStatic.CollectionItemsParameter.GlueNailBatch,
                        EquipNum = _parameterStatic.CollectionItemsParameter.EquipNum,
                        ProductionLineNo = _parameterStatic.CollectionItemsParameter.ProductionLineNo,
                        Operator = _temporaryStatic.Mes_Account,
                        ResultTotal = ResultTypes._,
                        RowNo = (byte)row,
                        ColunmNo = (byte)column,
                        Position = position,
                        //ResultScanCodeBefore = ResultTypes.合格,
                        //LocationScanCodeBefore = (byte)context.DeviceIndex,
                        WorkOrderNumber = _parameterStatic.CollectionItemsParameter.WorkOrder,
                        ResultOutput = ResultTypes._
                        //CollectionMethod = _parameterStatic.DecideParameter.EnableVariableInjection ? "变量注液" : "定量注液",
                        //ProductionMethod = _parameterStatic.DecideParameter.EnableReinvestmentMode ? "正常" : "复投",
                    };
                   
                    entity.ResultFormerWeighing = Range_Check(entity);

                    if (entity.ResultFormerWeighing == ResultTypes.合格)
                    {
                       
                        entity.TargetInjectionVolume = _parameterStatic.RangeParameter.Quantitative;

                        BatteryModel WriteInjectionModel = new BatteryModel();
                        WriteInjectionModel.ID = snowflake;
                        WriteInjectionModel.Data_PLC = (float)entity.TargetInjectionVolume;
                        WriteInjectionModel.Data_PC = (float)entity.TargetInjectionVolume;
                        //long aa = 16555304029237248;


                        if (plc.WriteClass(WriteInjectionModel, "PC_Result_Scales.BeforeWeight[0]", 35167))
                        {
                            RunLog($"-[前称重]写入注液量{entity.TargetInjectionVolume},位置{position},雪花ID:{snowflake}成功");
                        }
                        else
                        {
                            RunLog($"-[前称重]写入注液量{entity.TargetInjectionVolume},位置{position},雪花ID:{snowflake}失败", MessageLevelType.错误);
                            
                        }

                        //    if (!WriteInjectionVolume((float)entity.TargetInjectionVolume, plc, address_Struct, context))
                        //{
                        //    RunLog($"-[前称重]注液量发送失败标签:{address_Struct}");
                        //    entity.ResultFormerWeighing = ResultTypes.注液量写入失败;
                        //}
                        //else
                        //{
                        //    plc.WriteSingle((float)snowflake, $"{address_Struct}.PLCData");
                        //    RunLog($"-[前称重]写入注液量{entity.TargetInjectionVolume},位置{position},雪花ID:{snowflake}成功");
                        //}
                    }

                    RunLog($"-[前称重]条码{entity.BarCode} 位置：{entity.Position}开始总结果：{entity.ResultTotal}");
                    RunLog($"-[前称重]条码{entity.BarCode} 位置：{entity.Position}判断结果：{entity.ResultFormerWeighing}");

                    if (entity.ResultFormerWeighing != ResultTypes.合格 && entity.ResultTotal == ResultTypes._)
                    {
                        Interlocked.Increment(ref _weighingNG);
                        entity.ResultTotal = entity.ResultFormerWeighing;
                        _parameterStatic.WeighingConfig.CurrentLocation--;
                    }

                    for (int i = 0; i < 3; i++)
                    {
                        try
                        {
                            RunLog("开始插入数据库");
                            entity.Insert();
                            Locked();
                            entity.Items.Add("TableName", ProductionData.Meta.TableName);
                            _temporaryStatic.EntityCache.Insert(0, entity);
                            if (_temporaryStatic.EntityCache.Count > 600)
                            {
                                _temporaryStatic.EntityCache.RemoveAt(599);
                            }
                            UnLock();
                            RunLog($"-[{context.DeviceIndex}] ID:[{snowflake}]对应的条码为:[{barCode}]对应位置{position} 插入数据库成功");
                            break;
                        }
                        catch (Exception ex)
                        {
                            RunLog($"-[{context.DeviceIndex}] ID:[{snowflake}]对应的条码为:[{barCode}] 对应位置{position}第[{i}]次 保存数据库失败：{ex}");
                            Thread.Sleep(500);
                        }
                    }
                    //BatteryModel model = new BatteryModel();
                    //model.ID = snowflake;
                    //model.Results_PC = (short)(resultTypes == ResultTypes.合格 ? 1 : (resultTypes != ResultTypes.MES_NG ? 2 : 3));
                    //for (int i = 0; i < 3; i++)
                    //{
                    //    if (plc.WriteClass(model, $"{context.Address_Struct}.face", 35167))
                    //    {
                    //        RunLog($"-[{context.DeviceIndex}] ID:[{model.ID}] 结果:[{model.Results_PC}] 写入成功!!!");
                    //        break;
                    //    }
                    //    RunLog($"-[{context.DeviceIndex}] ID:[{model.ID}] 结果:[{model.Results_PC}] 写入失败 第[{i}]次");
                    //}
                    
                    WriteResult(entity.BarCode, entity.ResultTotal, plc, address_Struct, context);

                    _homeStatic.AddBeforeWeighingBattery(entity.BarCode, entity.ResultFormerWeighing, weighing_time, entity.FormerWeighing, 1, entity);

                }
                else
                {
                    //ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.Position == position);
                    RunLog($"后称重触发，电池位置[{position}]", MessageLevelType.警告);
                    entity = _temporaryStatic.EntityCache
                             .Where(x => x.Position == position) // 添加筛选条件
                             .OrderByDescending(x => DateTimeOffset.FromUnixTimeMilliseconds(x.TimeFormerWeighing)) // 转换为 DateTime，按时间戳降序排序
                             .FirstOrDefault(); // 获取第一条数据（最新的数据）

                    if (entity == null)
                    {
                        RunLog($"-[{1}] 实体缓存查询不到==>位置[{position}]，转到数据库查询");
                        entity = dateTime.GetEntity(context.TaskType, position);
                    }
                    else
                    {
                        ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                    }
                    if (entity == null)
                    {
                        RunLog($"-[{1}] 数据库找不到位置为：{position}");
                        WriteResult("", ResultTypes.数据库找不到电池, plc, address_Struct, context);
                        return base.Handle(context);
                    }

                    entity.TimeAfterWeighing = weighing_time.GetJSTimeUtc();
                    entity.LocationAfterWeighing = 1;
                    if (entity.AfterWeighing > _parameterStatic.RangeParameter.WeighAfterDown)
                    {
                        //说明已经称过重量了
                        WriteResult(entity.BarCode, entity.ResultTotal, plc, address_Struct, context);
                        RunLog($"-[后称重]条码{entity.BarCode}位置：{position}已经称过重了");
                        return base.Handle(context);
                    }
                    if (_parameterStatic.DecideParameter.EnableEmptyRun)
                    {
                        weiging = new Random().Next((int)_parameterStatic.RangeParameter.WeighAfterDown, (int)_parameterStatic.RangeParameter.WeighAfterUp);
                    }
                    else
                    {
                        //weiging = GetWeiging(device, entity.BarCode);
                    }
                    //if ((weiging == null || weiging < 20) && !_parameterStatic.DecideParameter.EnableEmptyRun)
                    //{
                    //    RunLog($"后称重[{entity.BarCode}] [{1}]号不稳定报警", MessageLevelType.警告);
                    //    alarm = true;
                    //    //_parameterStatic.WeighingConfig.CurrentLocation--;
                    //    //WriteCMD(1, plc, _systemConfig.IAddress.Alarm_BeforeWeighing);

                    //    //return base.Handle(context);
                    //}
                    entity.AfterWeighing = weiging == null ? 0 : (double)weiging;
                    if (_systemConfig.SCM.MainDeviceType == MainDeviceTypeEnum.一次注液)
                        entity.OneAfterWeighing = entity.AfterWeighing;

                    entity.ActualInjectionVolume = Math.Round(entity.AfterWeighing - entity.FormerWeighing, 2, MidpointRounding.AwayFromZero);
                    entity.InjectionVolumeDeviationValue = Math.Round(entity.ActualInjectionVolume - entity.TargetInjectionVolume, 2, MidpointRounding.AwayFromZero);
                    entity.ActualTotalInjectionVolume = Math.Round(entity.AfterWeighing - entity.NetWeight, 2, MidpointRounding.AwayFromZero);
                    entity.ResultAfterWeighing = InjRange_Check(entity, 1);
                    entity.LocationAfterWeighing = (byte)position;
                    try
                    {
                        //PC_Result_Scales.AfterWeight[0].ID

                        #region 后称重数据获取
                        BatteryLiquidInjectionDataModel injectionDataModel = new BatteryLiquidInjectionDataModel();
                        plc.ReadClass($"PC_AfterWeightData[1]", injectionDataModel);
                        RunLog($"-[1] 后称重数据==>>{System.Text.Json.JsonSerializer.Serialize(injectionDataModel, GlobalStatic.Options)}");
                        #endregion
                        #region 实体赋值
                        entity.LeakVacuum = injectionDataModel.LeakVacuum;
                        entity.LeakResult = injectionDataModel.VcheckResult == 1 ? ResultTypes.合格 : ResultTypes.测漏NG;
                        entity.RowNo = (byte)injectionDataModel.RowNo;
                        entity.ColunmNo = (byte)injectionDataModel.ColunmNo;
                        entity.InjectionPumpNo = (byte)injectionDataModel.InjectionPumpNo;
                        entity.CylinderNo = (byte)injectionDataModel.CylinderNo;
                        entity.LayerNumber = (byte)injectionDataModel.LayerNumber;
                        entity.InjectionTime = injectionDataModel.InjectionTime;
                        entity.CycleTime = injectionDataModel.CycleTime;
                        entity.FillingCup = (byte)injectionDataModel.InjectionNozzle;
                        entity.CycleNumber = (byte)injectionDataModel.CycleNumber;
                        entity.InjBeforeVacuum = injectionDataModel.InjBeforeVacuum;
                        entity.InjAfterVacuum = injectionDataModel.InjAfterVacuum;
                        entity.InjPressure = injectionDataModel.InjPressure;
                        //entity.CyclicPressurizationValue = CyclicPressurizationValue;
                        //entity.CirculatingVacuumValue = CirculatingVacuumValue;
                        entity.StationNo = injectionDataModel.InjectionStationNo.ToString();
                        RunLog($"-[{entity.BarCode}] 电池数据==>>{System.Text.Json.JsonSerializer.Serialize(entity, GlobalStatic.Options)}");
                        #endregion
                    }
                    catch (Exception ex)
                    {

                        RunLog($"-[后称重] 读取PLC数据异常：{ex}");
                        WriteCMD(1, plc, _systemConfig.IAddress.Erinnerungen_AfterWeighing);
                        WriteResult("", ResultTypes.不合格, plc, address_Struct, context);
                        return base.Handle(context);
                    }


                    RunLog($"-[后称重]条码{entity.BarCode}开始总结果：{entity.ResultTotal}");
                    RunLog($"-[后称重]条码{entity.BarCode}称重结果：{entity.ResultAfterWeighing}");

                    if (entity.LeakResult != ResultTypes.合格 && entity.ResultTotal == ResultTypes._)
                        entity.ResultTotal = entity.LeakResult;

                    if (entity.ResultAfterWeighing != ResultTypes.合格 && entity.ResultTotal == ResultTypes._)
                    {
                        Interlocked.Increment(ref _weighingNG);
                        entity.ResultTotal = entity.ResultAfterWeighing;
                    }
                    
                    
                    if (entity.LeakResult == ResultTypes.合格)
                    {
                        if (entity.ResultAfterWeighing == ResultTypes.注液量偏多)
                        {
                            Interlocked.Increment(ref _multiLiquid);
                        }
                        if (entity.ResultAfterWeighing == ResultTypes.注液量偏少)
                        {
                            Interlocked.Increment(ref _lessLiquid);
                            var refillInj = (float)Math.Abs(entity.TotalInjectionVolumeDeviationValue);
                            if (!WriteInjectionVolume(refillInj, plc, address_Struct, context))
                            {
                                entity.ResultAfterWeighing = ResultTypes.补液量写入失败;
                                if (entity.ResultTotal == ResultTypes._)
                                    entity.ResultTotal = entity.ResultAfterWeighing;
                            }
                        }
                    }
                    else
                    {
                        Interlocked.Increment(ref _LeakDetectionNG);
                    }
                    Interlocked.Increment(ref _total);
                    try
                    {

                        entity.Update();
                    }
                    catch (Exception ex)
                    {
                        RunLog($"-[{1}] 数据库保存异常：{ex}");
                        WriteCMD(1, plc, _systemConfig.IAddress.Alarm_AfterWeighing);
                        WriteResult("", ResultTypes.不合格, plc, address_Struct, context);
                        return base.Handle(context);
                    }



                    RunLog($"-[后称重]条码{entity.BarCode}结束总结果：{entity.ResultTotal}");
                    //RunLog($"-[{battery.Index}] ID：[{battery.SnowflakeId}] 条码：[{entity.BarCode}]");
                    WriteResult(entity.BarCode, entity.ResultTotal, plc, address_Struct, context);

                    var tm = _homeStatic.Trend.FirstOrDefault(k => k.Name == $"{entity.StationNo}_{entity.InjectionPumpNo}_{entity.FillingCup}");
                    if (tm != null)
                    {
                        System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
                        {
                            tm.InjectionVolumeCollection.Add(entity.ActualInjectionVolume);
                            if (tm.InjectionVolumeCollection.Count > 50)
                            {
                                tm.InjectionVolumeCollection.Remove(0);
                            }
                            if (tm.InjectionVolumeCollection.Count > 10)
                            {
                                tm.ProcessCapability.USL = _parameterStatic.RangeParameter.QuantitativeUp;
                                tm.ProcessCapability.LSL = _parameterStatic.RangeParameter.QuantitativeDown;
                                tm.ProcessCapability.U = _parameterStatic.RangeParameter.Quantitative;
                                tm.ProcessCapability.T = Math.Round(tm.ProcessCapability.USL - tm.ProcessCapability.LSL, 2, MidpointRounding.AwayFromZero);
                                tm.ProcessCapability.X = tm.InjectionVolumeCollection.AsParallel().Average();
                                tm.StandardDeviation = tm.ProcessCapability.X;
                                tm.ProcessCapability.SpecificationStandardDeviation = GetSpecificationStandardDeviation(tm.InjectionVolumeCollection.ToList(), tm.ProcessCapability);
                                tm.ProcessCapability.CA = GetCa(tm.ProcessCapability);
                                tm.ProcessCapability.CP = GetCp(tm.ProcessCapability);
                                tm.ProcessCapability.CPK = GetCpk(tm.ProcessCapability);
                                tm.CPK = tm.ProcessCapability.CPK;
                                tm.Deviation = tm.ProcessCapability.CA;
                            }
                        });
                    }
                    _homeStatic.AddOutBattery(entity);
                    _homeStatic.AddAfertWeighingBattery(entity.BarCode, entity.ResultAfterWeighing, weighing_time, entity.AfterWeighing, 1, entity);
                    //Parallel.ForEach(erinnerungen.Item2, battery =>
                    //{
                    //    //#region 获取加压缸数据（二期）
                    //    //List<BatteryPressureModel> batteryPressureList = new List<BatteryPressureModel>();

                    //    //BatteryPressureArrayModel batteryPressureModel = new BatteryPressureArrayModel(31);
                    //    //plc.ReadClass($"PC_TankMES", batteryPressureModel);
                    //    //batteryPressureList.AddRange(batteryPressureModel.Data);
                    //    //RunLog($"加压缸数据==>>{System.Text.Json.JsonSerializer.Serialize(batteryPressureList, GlobalStatic.Options)}");

                    //    //var CyclicPressurizationValue = 0f;//加压
                    //    //var CirculatingVacuumValue = 0f;//真空
                    //    //var ba = batteryPressureList.Where(x => x.FunType == 2).ToList();
                    //    //if (ba.Count > 0)
                    //    //{
                    //    //    CyclicPressurizationValue = ba.Max(x => x.Value);
                    //    //}

                    //    //var be = batteryPressureList.Where(x => x.FunType == 1).ToList();
                    //    //if (be.Count > 0)
                    //    //{
                    //    //    CirculatingVacuumValue = be.Min(x => x.Value);
                    //    //}

                    //    //RunLog($"加压缸数据==>>真空：{CirculatingVacuumValue}，加压：{CyclicPressurizationValue}");
                    //    //#endregion


                    //});

                }

                _parameterStatic.Save();
                #region 图表统计
                if (_parameterStatic.WeighingConfig.ScaleType == TaskTypes.前称重)
                {
                    _homeStatic.ChartData.NG_BeforeWeighin += _weighingNG;
                    _homeStatic.ChartData.PassingRateInbound = Math.Round((double)(1 - ((_homeStatic.ChartData.NG_BeforeWeighin + _homeStatic.ChartData.NG_ScanCode) / _homeStatic.ChartData.Total_Inbound)), 4, MidpointRounding.AwayFromZero);
                }
                else if (_parameterStatic.WeighingConfig.ScaleType == TaskTypes.后称重)
                {
                    lock (locker)
                    {
                        _homeStatic.ChartData.Total_LiquidInjection ++;
                        _homeStatic.ChartData.NG_MultiLiquid += _multiLiquid;
                        _homeStatic.ChartData.OV_MultiLiquid.Value = _homeStatic.ChartData.NG_MultiLiquid;
                        _homeStatic.ChartData.NG_LessLiquid += _lessLiquid;
                        _homeStatic.ChartData.NG_LeakDetection += _LeakDetectionNG;
                        _homeStatic.ChartData.OV_LessLiquid.Value = _homeStatic.ChartData.NG_LessLiquid;
                        _homeStatic.ChartData.NG_LiquidInjection += _weighingNG;
                        var _passingRate = Math.Round((_homeStatic.ChartData.Total_LiquidInjection - (_homeStatic.ChartData.NG_MultiLiquid + _homeStatic.ChartData.NG_LessLiquid)) / _homeStatic.ChartData.Total_LiquidInjection, 4, MidpointRounding.ToNegativeInfinity);
                        _homeStatic.ChartData.LiquidInjection_PassingRate = _passingRate > 1 ? 1 : _passingRate;
                        _homeStatic.ChartData.OV_LiquidInjection_PassingRate.Value = _homeStatic.ChartData.LiquidInjection_PassingRate;
                    }
                }

                #endregion

                //if (alarm) { WriteCMD(1, plc, _systemConfig.IAddress.Alarm_BeforeWeighing); }

            }
            catch (Exception ex)
            {
                RunLog($"异常：{ex}");
            }
            return base.Handle(context);
        }

        /// <summary>
        /// 样本标准差
        /// </summary>
        /// <param name="sixSigma"></param>
        /// <returns></returns>
        static double GetSpecificationStandardDeviation(List<double> valueList, ProcessCapabilityModel sixSigma) => Math.Sqrt(valueList.AsParallel().Select(item => Math.Pow(item - sixSigma.X, 2)).Sum() / (valueList.Count - 1));

        /// <summary>
        /// 表示制程特性的一致程度，值越大越集中
        /// </summary>
        /// <param name="sixSigma"></param>
        /// <returns></returns>
        static double GetCp(ProcessCapabilityModel sixSigma) => sixSigma.T / (6 * sixSigma.SpecificationStandardDeviation);

        /// <summary>
        /// Ca====表示制程特性中心位置的偏移程度
        /// </summary>
        /// <param name="sixSigma"></param>
        /// <returns></returns>
        static double GetCa(ProcessCapabilityModel sixSigma) => (sixSigma.X - sixSigma.U) / (sixSigma.T / 2);

        /// <summary>
        /// 考虑偏移及一致程度
        /// </summary>
        /// <param name="sixSigma"></param>
        /// <returns></returns>
        static double GetCpk(ProcessCapabilityModel sixSigma)
        {
            sixSigma.CpkU = Math.Abs(sixSigma.USL - sixSigma.X) / (3 * sixSigma.SpecificationStandardDeviation);
            sixSigma.CpkL = Math.Abs(sixSigma.X - sixSigma.LSL) / (3 * sixSigma.SpecificationStandardDeviation);
            return Math.Min(sixSigma.CpkU, sixSigma.CpkL);
        }

        public static string GenerateUniqueBarcode(string position)
        {
            long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds(); // 获取当前时间戳（毫秒级）
            string barcode = timestamp.ToString(); // 将时间戳转换为字符串
            return $"TP{position}{barcode}";
        }
        private ResultTypes Range_Check(ProductionData entity)
        {
            if (!_parameterStatic.DecideParameter.EnableBeforeInjection)
            {
                RunLog($"请注意!!![{entity.BarCode}] 未启用前称重检查==>>强制合格");
                return ResultTypes.合格;
            }
            string[] range = entity.RangeForeweigh.Split('-');
            double down = Convert.ToDouble(range[0]);
            double up = Convert.ToDouble(range[1]);
            return entity.FormerWeighing switch
            {
                var k when k <= up && k >= down => ResultTypes.合格,
                var k when k > up => ResultTypes.称重偏重,
                var k when k < down => ResultTypes.称重偏轻,
                _ => ResultTypes.不合格,
            };
        }
    }
}
